﻿#include "serialthread.h"
#include <QDebug>

SerialThread::SerialThread()
{
    moveToThread(this);
}

SerialThread::~SerialThread()
{
    if (m_serial->isOpen())
        m_serial->close();
}

void SerialThread::run()
{
    qDebug() << "serial "<<QThread::currentThreadId();
    m_serial = new QSerialPort();
    m_timer = new QTimer();
    open("COM3");
    exec();
}

bool SerialThread::open(QString serialName, int baudRate)
{
    // 设置串口名
    m_serial->setPortName(serialName);
    // 打开串口(以读写方式)
    if(m_serial->open(QIODevice::ReadWrite))
    {
        m_serial->setBaudRate(baudRate); // 设置波特率(默认为9600)
        m_serial->setDataBits( QSerialPort::Data8 ); // 设置数据位(数据位为8位)
        m_serial->setParity( QSerialPort::NoParity ); // 设置校验位(无校验位)
        m_serial->setStopBits( QSerialPort::OneStop ); // 设置停止位(停止位为1)
        m_serial->setFlowControl( QSerialPort::NoFlowControl ); // 设置流控制(无数据流控制)

        // 当下位机中有数据发送过来时就会响应这个槽函数
        QIODevice::connect(m_serial, &QSerialPort::readyRead, this, &SerialThread::delay);
        connect(m_timer,&QTimer::timeout, this, &SerialThread::readData);
        // 当下位机中有数据发送过来时就会触发这个信号，以提示其它类对象
        //connect(m_serial, SIGNAL(readyRead()), this, SIGNAL(readSignal()));

        return true;
    }

    return false;
}

void SerialThread::slt_writeData(const QByteArray &data)
{
    m_serial->write(data);
}

void SerialThread::readData()
{
    m_timer->stop();
    QByteArray data = m_serial->read(29);
    /*
    for(int i=0;i<29;i++)
        qDebug()<<(data.at(i) & 0x000000ff )<<" ";
        */
    SerialPack pack;
    //2~4
    pack.ip = 173;
    //pack.ip = data.at(2) & 0x000000ff;//5~7
    pack.settings.inject_volume = (data.at(6)& 0x000000ff << 8 ) + data.at(7) & 0x000000ff;// 9~10
    pack.settings.inject_period = (data.at(8)& 0x000000ff << 8 ) + data.at(9)& 0x000000ff;//11~12 ( 8, 9
    pack.settings.comm_period = (data.at(14)& 0x000000ff << 8 )+ data.at(15)& 0x000000ff;//17~18 ( 14, 15

    pack.isfirst = data.at(5)& 0x000000ff; //8
    pack.battery = data.at(10)& 0x000000ff; //13
    pack.oil = (data.at(11)& 0x000000ff << 8) + data.at(12)& 0x000000ff; // 14~15 (11, 12
    pack.status = data.at(13)& 0x000000ff; //16
    qDebug() << "serial data received"<<endl;

    emit sig_serialData(pack);
}

QStringList SerialThread::scanSerial()
{
    QStringList serialStrList;

    // 读取串口信息
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        m_serial->setPort(info);
        if(m_serial->open(QIODevice::ReadWrite))
        {
            serialStrList.append(m_serial->portName());
            m_serial->close();
        }
    }

    return serialStrList;
}

void SerialThread::close()
{
    if (m_serial->isOpen())
        m_serial->close();
}
void SerialThread::delay()
{
    m_timer->start(100);
}
